package com.gopay.bis.web.controller.tpas;

import java.util.Enumeration;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gopay.bis.common.util.CallCPSUtil;
import com.gopay.bis.service.bank.TpasOrderService;
import com.gopay.common.constants.bank.tpas.TpasMwaChargeConstants;
import com.gopay.common.constants.bank.tpas.TpasOrderStatus;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.tpas.TpasMessage;
import com.gopay.common.domain.bank.tpas.TpasResult;
import com.gopay.common.domain.bank.tpas.mwa.MobileMessage;
import com.gopay.common.domain.cps.vo.CPSResponse;
import com.gopay.common.domain.cps.wallet.Wallet01611Vo;
import com.gopay.common.domain.cps.wallet.Wallet01612VO;
import com.gopay.common.domain.cps.wallet.Wallet01613Vo;
import com.gopay.remote.bank.TpasChargeInteractRemoteService;

@Controller
@Scope("prototype")
public class OfpayRes {
    private static Log logger = LogFactory.getLog(OfpayRes.class);
    
    @Resource(name = "bisConfig")
	protected Map<String, String> bisConfig;
    @Resource(name="bisTpasChargeService")
    private TpasChargeInteractRemoteService bisTpasChargeService;
    @Resource(name = "tpasOrderService")
    protected TpasOrderService tpasOrderService;
    
    @RequestMapping(value = "/ofpayChargeRes")
    public void execute(HttpServletRequest request,HttpServletResponse response){
        for (Enumeration enumeration = request.getParameterNames(); enumeration.hasMoreElements();) {
            String eleName = (String) enumeration.nextElement();
            String eleValue = request.getParameter(eleName);
            if (logger != null) {
                logger.error("map key: [" + eleName + "]，value: [" + eleValue+ "]");
            }
        }
        String outOrderId = request.getParameter("sporder_id");
        String retCode = request.getParameter("ret_code");
        TpasMessage msg = new MobileMessage();
        msg.setOutOrderId(outOrderId);
        msg.setRetCode(retCode);
        try {
            TpasResult result = bisTpasChargeService.tpasBack(msg);
            TpasMessage res = (TpasMessage)result.getDefaultModel();
            boolean success = result.isSuccess();
            if(!success)
            	return;//内部处理失败
            if(TpasMwaChargeConstants.CHARGE_SUCCESS.equals(res.getRetCode()))
            	success = true;
            else if(TpasMwaChargeConstants.CHARGE_FAIL.equals(res.getRetCode()))
            	success = false;
            //通知
            String transType = result.getTransType();
            CPSResponse cpsres = null; 
            try {
				switch (transType) {
					case "01611":
						Wallet01611Vo vo01611 = new Wallet01611Vo();
						vo01611.setSuccess(success);
						vo01611.setGopayOrderId(result.getOrderid());
						vo01611.setStep(1);
						cpsres = CallCPSUtil.callByVOTicket(vo01611);
						break;
					case "01612":
						Wallet01612VO vo01612 = new Wallet01612VO();
						vo01612.setProcStatus(success);
						vo01612.setGopayOrderId(result.getOrderid());
						vo01612.setOprStep("2");
						cpsres = CallCPSUtil.callByVOTicket(vo01612);
						break;
					case "01613":
						Wallet01613Vo vo01613 = new Wallet01613Vo();
						vo01613.setSuccess(success);
						vo01613.setGopayOrderId(result.getOrderid());
						vo01613.setStep(1);
						cpsres = CallCPSUtil.callByVOTicket(vo01613);
						break;
					default:
						break;
					}
			} catch (Exception e) {
				logger.error(String.format("银行订单%s,gopayorderid：%s,bis notifyCps error: ", outOrderId, result.getOrderid()), e);
				if(success)
                	// 成功订单，若通知cashier异常,状态置为96自动对账处理
					tpasOrderService.updateInAcctFail(outOrderId, TpasOrderStatus.ENTER_ACCOUNT_FIAL); 
				else
					tpasOrderService.updateInAcctFail(outOrderId, TpasOrderStatus.FAIL_ACCOUNT_FIAL); 
			}
            if (ProcCodeConstants.PROC_CODE_100S1000.equals(cpsres.getRespCode()) 
            		|| ProcCodeConstants.PROC_CODE_000S1000.equals(cpsres.getRespCode())) {
            	logger.error(String.format("银行订单%s入账通知成功!!!!gopayorderid：%s", outOrderId, result.getOrderid()));
            }else{
            	logger.error(String.format("银行订单%s入账通知失败!!!!gopayorderid：%s,respcode:%s", outOrderId, result.getOrderid(), cpsres.getRespCode()));
            	if(success)
                	// 成功订单，若通知cashier异常,状态置为96自动对账处理
					tpasOrderService.updateInAcctFail(outOrderId, TpasOrderStatus.ENTER_ACCOUNT_FIAL); 
				else
					tpasOrderService.updateInAcctFail(outOrderId, TpasOrderStatus.FAIL_ACCOUNT_FIAL); 
            }
            
        } catch (Exception e) {
        	logger.error("ofpay res error!!! bankorderid=" + outOrderId, e);
        }
    }
}
